package com.wing.res.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.service.ProductDetailService;
import com.wing.res.dao.ResProductDrawDao;
import com.wing.res.model.entity.ResProTask;
import com.wing.res.model.entity.ResProductDraw;
import com.wing.res.model.entity.ResProductDrawPic;
import com.wing.res.model.request.ResDrawVersionUpdateForm;
import com.wing.res.model.response.DrawInfosVO;
import com.wing.res.model.response.ResProductDrawVo;
import com.wing.res.service.ResProTaskService;
import com.wing.res.service.ResProductDrawService;
import com.wing.sell.model.entity.CustomerProductCatalog;
import com.wing.sell.model.entity.OrderProEnclosure;
import com.wing.sell.service.CustomerProductCatalogService;
import com.wing.sell.service.OrderProEnclosureService;
import com.wing.web.excel.DrawExcelIn;
import com.wing.web.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * sku产品图纸-ServiceImpl
 *
 * @version 1.1.0
 * @Author hz
 * @Date 2024-09-23 20:59
 **/
@Service
public class ResProductDrawServiceImpl extends ServiceImpl<ResProductDrawDao, ResProductDraw> implements ResProductDrawService {

    @Resource
    private CustomerProductCatalogService catalogService;

    @Resource
    private OrderProEnclosureService orderProEnclosureService;

    @Resource
    private ResProTaskService resProTaskService;

    /**
     * 查询图纸列表
     *
     * @param pg
     * @return
     */
    @Override
    public Page<ResProductDrawVo> getListByMap(Page<ResProductDrawVo> pg, Map<String, Object> map) {
        return this.baseMapper.getListByMap(pg, map);
    }

    /**
     * 作废
     *
     * @param id
     * @return
     */
    @Override
    public int cancellation(String id) {
        ResProductDraw byId = this.getById(id);
        if (ObjectUtil.isNotEmpty(byId)) {
            if ("1".equals(byId.getIsDefault())) {
                return -1;
            }
            byId.setModifier(JwtUtils.getLoginUserId());
            byId.setUpdateTime(LocalDateTime.now());
            byId.setModifierName(JwtUtils.getLoginUsername());
            byId.setIsDeleted(true);
            boolean b = this.updateById(byId);
            if (b) {
                return 1;
            } else {
                return 0;
            }
        }
        return 0;
    }

    /**
     * 恢复图纸
     *
     * @param id
     * @return
     */
    @Override
    public int recover(String id) {
        ResProductDraw byId = this.getById(id);
        if (ObjectUtil.isNotEmpty(byId)) {
            byId.setModifier(JwtUtils.getLoginUserId());
            byId.setUpdateTime(LocalDateTime.now());
            byId.setModifierName(JwtUtils.getLoginUsername());
            byId.setIsDeleted(false);
            boolean b = this.updateById(byId);
            if (b) {
                return 1;
            } else {
                return 0;
            }
        }
        return 0;
    }

    /**
     * 设为默认
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int setDefault(String id) {
        ResProductDraw byId = this.getById(id);
        //设置为默认
        //将所有的设置为非默认
        Long taskId = byId.getTaskId();
        UpdateWrapper<ResProductDraw> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("task_id", taskId)
                .set("is_default", "0").set("modifier", JwtUtils.getLoginUserId())
                .set("modifier_name", JwtUtils.getLoginUsername()).set("update_time", LocalDateTime.now());
        update(updateWrapper);

        UpdateWrapper<ResProductDraw> updateOne = new UpdateWrapper<>();
        updateOne.eq("id", id)
                .set("is_default", "1").set("modifier", JwtUtils.getLoginUserId())
                .set("modifier_name", JwtUtils.getLoginUsername()).set("update_time", LocalDateTime.now());
        update(updateOne);
        return 1;
    }

    /**
     * 变更图纸版本
     *
     * @param form
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDrawVersion(ResDrawVersionUpdateForm form) {
        //如果是客户研发信息
        if ("1".equals(form.getType())) {
            QueryWrapper<CustomerProductCatalog> catalogQueryWrapper = new QueryWrapper<>();
            catalogQueryWrapper.eq("cus_product_code", form.getOrderProNo());
            CustomerProductCatalog cataLog = catalogService.getOne(catalogQueryWrapper);
            if (ObjectUtil.isNotEmpty(cataLog)) {
                //查询客户产品表
                QueryWrapper<OrderProEnclosure> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_id", cataLog.getId());
                OrderProEnclosure one = orderProEnclosureService.getOne(queryWrapper);
                if (ObjectUtil.isNotEmpty(one)) {
                    one.setTechnologyRemark(form.getRemark());
                    one.setFileUrl(form.getFileUrl());
                    one.setFileName(form.getName());
                    one.setUpdateTime(LocalDateTime.now());
                    one.setModifier(JwtUtils.getLoginUserId());
                    one.setModifierName(JwtUtils.getLoginUsername());
                    one.setTechnologyRemark(form.getRemark());
                    orderProEnclosureService.updateById(one);
                }
            }
        }else if("2".equals(form.getType())){
            //taskId
            ResProTask resProTask = resProTaskService.getById(form.getTaskId());
            //拿到关联的附件id
            if (ObjectUtil.isNotEmpty(resProTask)){
                Long zyEnclosureId = resProTask.getZyEnclosureId();
                OrderProEnclosure enclosure = orderProEnclosureService.getById(zyEnclosureId);
                if (ObjectUtil.isNotEmpty(enclosure)){
                    enclosure.setTechnologyRemark(form.getRemark());
                    enclosure.setFileUrl(form.getFileUrl());
                    enclosure.setFileName(form.getName());
                    enclosure.setUpdateTime(LocalDateTime.now());
                    enclosure.setModifier(JwtUtils.getLoginUserId());
                    enclosure.setModifierName(JwtUtils.getLoginUsername());
                    enclosure.setTechnologyRemark(form.getRemark());
                    orderProEnclosureService.updateById(enclosure);
                }
            }
        }
        //自研产品
        ResProductDraw byId = this.getById(form.getDrawId());
        if (ObjectUtil.isNotEmpty(byId)) {
            byId.setIsDefault("0");
            byId.setUpdateTime(LocalDateTime.now());
            byId.setModifier(JwtUtils.getLoginUserId());
            byId.setModifierName(JwtUtils.getLoginUsername());
            this.updateById(byId);

            byId.setId(null);
            byId.setCreateTime(LocalDateTime.now());
            byId.setCreator(JwtUtils.getLoginUserId());
            byId.setCreatorName(JwtUtils.getLoginUsername());
//            byId.setFileUrl(form.getFileUrl());
            byId.setRemark(form.getRemark());
//            byId.setName(form.getName());
            byId.setVersionName(UniqueIdGeneratorUtil.generateUniqueId("", "yyyyMMdd", 1000, 9999));
            byId.setIsDefault("1");
            this.save(byId);
        }
        return 1;
    }

    /**
     * 查询所有的图纸信息
     * @param id
     * @param skuId
     * @return
     */
    @Override
    public Integer getCountForDraw(Long id, Long skuId) {
        return this.baseMapper.getCountForDraw(id,skuId);
    }


    @Resource
    ProductDetailService productDetailService;

    @Override
    public void importExcel(List<DrawExcelIn> list) {
        int i = 1;
        for (DrawExcelIn productDetail : list) {
            if (StringUtils.isBlank(productDetail.getFileUrl())) {
                throw new BusinessException(300, "第" + i + "行【附件地址】未输入数据");
            }
            if (StringUtils.isBlank(productDetail.getProductDetailId())) {
                throw new BusinessException(300, "第" + i + "行【sku物料】未输入数据");
            }
            if (StringUtils.isBlank(productDetail.getDrawType())) {
                throw new BusinessException(300, "第" + i + "行【图纸类型】未输入数据");
            }
            if (StringUtils.isBlank(productDetail.getName())) {
                throw new BusinessException(300, "第" + i + "行【产品图纸名称】未输入数据");
            }
            if (StringUtils.isBlank(productDetail.getCode())) {
                throw new BusinessException(300, "第" + i + "行【产品图纸Code】未输入数据");
            }
            if (StringUtils.isBlank(productDetail.getVersionName())) {
                throw new BusinessException(300, "第" + i + "行【版本名称】未输入数据");
            }
            ResProductDraw drawPic=new ResProductDraw();
            // 1.成品图纸 2.工序图纸 3模具图纸  todu-hz
//            if(productDetail.getDrawType().equals("成品图纸")){
//                drawPic.setDrawType("1");
//            }else  if(productDetail.getDrawType().equals("工序图纸")){
//                drawPic.setDrawType("2");
//            }else  if(productDetail.getDrawType().equals("模具图纸")){
//                drawPic.setDrawType("3");
//            }
//            drawPic.setFileUrl(productDetail.getFileUrl());

            ProductDetail productDetailList = productDetailService.getProductDetailBySkuCodeNo(productDetail.getProductDetailId());
            if(productDetailList!=null){
                drawPic.setProductDetailId(productDetailList.getId());
            }

//            drawPic.setName(productDetail.getName());
            drawPic.setCode(productDetail.getCode());
            drawPic.setVersionName(productDetail.getVersionName());
            drawPic.setIsRelevance("1");
            baseMapper.insert(drawPic);
        }




    }

    /**
     * 查询基准书图纸信息
     * @param id
     * @return
     */
    @Override
    public List<DrawInfosVO> getDrawInfosBy(String id) {
        return baseMapper.getDrawInfosBy(id);
    }


}
